#ifndef CODE_ANALYZER_H
#define CODE_ANALYZER_H

#include <map>
#include <string>
#include <vector>
#include <set>
#include "ASTNode.h"
#include "OptimizationCostModel.h"

// 代码特征类型
enum class CodeFeature {
    SIMPLE_EXPRESSIONS,      // 简单表达式
    COMPLEX_EXPRESSIONS,     // 复杂表达式
    CONSTANT_EXPRESSIONS,    // 常量表达式
    COMMON_SUBEXPRESSIONS,   // 公共子表达式
    UNUSED_VARIABLES,        // 未使用变量
    DEAD_CODE,               // 死代码
    LOOPS,                   // 循环结构
    CONDITIONALS,            // 条件语句
    FUNCTION_CALLS,          // 函数调用
    NESTED_STRUCTURES,       // 嵌套结构
    MATRIX_OPERATIONS,       // 矩阵运算
    RECURSIVE_FUNCTIONS,     // 递归函数
    SIDE_EFFECTS,            // 副作用
    MEMORY_INTENSIVE,        // 内存密集型
    COMPUTE_INTENSIVE        // 计算密集型
};

// 代码复杂度级别
enum class ComplexityLevel {
    VERY_SIMPLE = 0,
    SIMPLE = 1,
    MODERATE = 2,
    COMPLEX = 3,
    VERY_COMPLEX = 4
};

// 代码特征统计
struct CodeFeatureStats {
    int totalNodes;
    int expressionNodes;
    int constantExpressions;
    int variableReferences;
    int functionCalls;
    int loops;
    int conditionals;
    int assignments;
    int unusedVariables;
    int deadCodeStatements;
    int nestedLevels;
    int matrixOperations;
    int recursiveCalls;

    // 复杂度指标
    double averageExpressionComplexity;
    int maxNestingDepth;
    int cyclomaticComplexity;
    double codeDensity;

    CodeFeatureStats() : totalNodes(0), expressionNodes(0), constantExpressions(0),
                        variableReferences(0), functionCalls(0), loops(0), conditionals(0),
                        assignments(0), unusedVariables(0), deadCodeStatements(0),
                        nestedLevels(0), matrixOperations(0), recursiveCalls(0),
                        averageExpressionComplexity(0.0), maxNestingDepth(0),
                        cyclomaticComplexity(1), codeDensity(0.0) {}
};

// 优化策略建议
struct OptimizationStrategy {
    ComplexityLevel complexityLevel;
    std::vector<OptimizationType> recommendedOptimizations;
    std::vector<OptimizationType> optionalOptimizations;
    std::vector<OptimizationType> aggressiveOptimizations;
    int suggestedOptimizationLevel;
    std::string reasoning;

    OptimizationStrategy() : complexityLevel(ComplexityLevel::SIMPLE), suggestedOptimizationLevel(1) {}
};

// 代码特征分析器
class CodeAnalyzer {
private:
    CodeFeatureStats stats;
    std::set<CodeFeature> detectedFeatures;
    std::map<std::string, int> variableUsage;
    std::map<std::string, int> expressionFrequency;
    std::set<std::string> definedVariables;
    std::set<std::string> usedVariables;

    // 分析辅助方法
    void analyzeNodeRecursively(ASTNode* node, int depth = 0);
    void analyzeExpression(ASTNode* node);
    bool isConstantExpression(ASTNode* node);
    std::string generateExpressionKey(ASTNode* node);
    void detectFeatures(ASTNode* node);
    void analyzeVariableUsage(ASTNode* node);
    void analyzeControlFlow(ASTNode* node);
    void analyzeFunctionCalls(ASTNode* node);
    void detectDeadCode(ASTNode* node);
    void calculateComplexityMetrics(ASTNode* node);
    void calculateDensityRecursive(ASTNode* node, int& meaningfulNodes, int& totalNodes);
    std::string generateReasoning();

    // 特征检测方法
    bool hasConstantExpressions(ASTNode* node);
    bool hasCommonSubexpressions(ASTNode* node);
    bool hasUnusedVariables();
    bool hasDeadCode(ASTNode* node);
    bool hasLoops(ASTNode* node);
    bool hasConditionals(ASTNode* node);
    bool hasMatrixOperations(ASTNode* node);
    bool hasRecursiveFunctions(ASTNode* node);
    bool hasSideEffects(ASTNode* node);

    // 复杂度计算方法
    int calculateExpressionComplexity(ASTNode* node);
    int calculateNestingDepth(ASTNode* node, int currentDepth = 0);
    int calculateCyclomaticComplexity(ASTNode* node);
    double calculateCodeDensity(ASTNode* node);

public:
    CodeAnalyzer();

    // 主要分析方法
    void analyzeCode(ASTNode* root);
    CodeFeatureStats getStats() const;
    std::set<CodeFeature> getDetectedFeatures() const;
    ComplexityLevel getComplexityLevel() const;

    // 优化策略建议
    OptimizationStrategy suggestOptimizationStrategy();
    int suggestOptimizationLevel();
    std::vector<OptimizationType> getRecommendedOptimizations();

    // 详细分析报告
    void generateAnalysisReport();
    void printFeatureSummary() const;
    void printComplexityAnalysis() const;

    // 重置分析器状态
    void reset();
};

#endif // CODE_ANALYZER_H
